package ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.factories.imp;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.Device;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.DeviceChangeListener;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.DeviceController;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.DeviceManager;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.factories.DeviceControllerFactory;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.factories.DeviceManagerFactory;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.factories.ModbusTransportFactory;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.imp.DeviceManagerImp;

@Component
public class DeviceManagerFactoryImp implements DeviceManagerFactory {
	
	@Autowired(required=true)
	private DeviceControllerFactory controllerFactory;
	@Autowired(required=true)
	private ModbusTransportFactory transportfactory;
	
	private Map<Integer,DeviceManager> managersCreated;
	
	public DeviceManagerFactoryImp(){
		managersCreated = new HashMap<Integer,DeviceManager>();
		managersCreated = Collections.synchronizedMap(managersCreated);
	}
	/**
	 * @return the controllerFactory
	 */
	public DeviceControllerFactory getControllerFactory() {
		return controllerFactory;
	}
	/**
	 * @param controllerFactory the controllerFactory to set
	 */
	public void setControllerFactory(DeviceControllerFactory controllerFactory) {
		this.controllerFactory = controllerFactory;
	}
	/**
	 * @return the transportfactory
	 */
	public ModbusTransportFactory getTransportfactory() {
		return transportfactory;
	}
	/**
	 * @param transportfactory the transportfactory to set
	 */
	public void setTransportfactory(ModbusTransportFactory transportfactory) {
		this.transportfactory = transportfactory;
	}
	@Override
	public DeviceManager create(Device device) {
		
		synchronized (this) {
			if(managersCreated.containsKey(device.getID()))
				return managersCreated.get(device.getID());
			
			DeviceManagerImp ret = new DeviceManagerImp();
			ret.setDevice(device);
			ret.setListeners(new ArrayList<DeviceChangeListener>());
			ret.setTransportfactory(transportfactory);
			
			DeviceController controller = controllerFactory.create(device);
			controller.setPImageListener(ret);
			ret.setController(controller);
			ret.initState();
			
			managersCreated.put(device.getID(), ret);
			return ret;
			
		}
		
	}

}
